package com.cnswhy.cloud.server.merchant.controller.shop;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cnswhy.cloud.common.core.base.R;
import com.cnswhy.cloud.common.core.base.controller.SuperController;
import com.cnswhy.cloud.common.core.base.request.PageParams;
import com.cnswhy.cloud.common.core.entity.CurrentUser;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.CnswhyUtil;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.core.constant.RedisConstant;
import com.cnswhy.cloud.server.core.dao.ShopProductMapper;
import com.cnswhy.cloud.server.core.dto.*;
import com.cnswhy.cloud.server.core.entity.*;
import com.cnswhy.cloud.server.core.service.ShopProductGalleryService;
import com.cnswhy.cloud.server.core.service.ShopProductSpecService;
import com.cnswhy.cloud.server.core.service.ShopSpecValueService;
import com.cnswhy.cloud.server.core.service.customer.CouponDetailService;
import com.cnswhy.cloud.server.core.service.shop.ShopProductService;
import com.cnswhy.cloud.server.core.service.shop.ShopProductStockService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//import com.github.zuihou.security.annotation.PreAuth;


/**
 * <p>
 * 前端控制器
 * 
 * </p>
 *
 * @author cnswhy
 * @date 2020-11-07
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/shopProduct")
@Api(value = "ShopProduct", tags = "")
//@PreAuth(replace = "couponDetail:")
public class ShopProductController extends SuperController<ShopProductService, Long, ShopProduct, ShopProductPageDTO, ShopProductSaveDTO, ShopProductUpdateDTO> {

    @Autowired
    ShopProductMapper shopProductMapper;
    @Autowired
    ShopProductGalleryService shopProductGalleryService;
    @Autowired
    ShopProductStockService shopProductStockService;
    @Autowired
    ShopProductSpecService shopProductSpecService;
    @Autowired
    ShopSpecValueService shopSpecValueService;
    @Autowired
    RedisService redisService;

    @Override
    public R<ShopProduct> handlerSave(ShopProductSaveDTO model) {
        CurrentUser currentUser = CnswhyUtil.getCurrentUser();
        log.info(JSON.toJSONString(currentUser));
        /*if(currentUser != null && currentUser.getMerchantId() != null){
            model.setMerchantId(currentUser.getMerchantId());
        }else{
            return R.fail("该用户不能添加商品");
        }*/
        model.setStatus(4);
        return R.successDef();
    }

    @Override
    public R<ShopProduct> handlerAfterSave(ShopProductSaveDTO shopProductSaveDTO, ShopProduct shopProduct) {
        if(shopProduct.getId() != null){
            List<ShopProductStock> shopProductStockList  = shopProductSaveDTO.getShopProductStockList();
            if(shopProductSaveDTO.getFlushStock()){
                shopProductStockService.remove(Wraps.<ShopProductStock>lbQ().eq(ShopProductStock::getProductId,shopProduct.getId()));
                for(ShopProductStock shopProductStock : shopProductStockList){
                    shopProductStock.setProductId(shopProduct.getId());
                }
                shopProductStockService.saveBatch(shopProductStockList);
            }else{

            }
            List<ShopProductGallerySaveDTO> shopProductGalleryList = shopProductSaveDTO.getShopProductGalleryList();
            for(ShopProductGallerySaveDTO shopProductGallerySaveDTO : shopProductGalleryList){
                ShopProductGallery model = BeanUtil.toBean(shopProductGallerySaveDTO, ShopProductGallery.class);
                model.setProductId(shopProduct.getId());
                shopProductGalleryService.save(model);
            }
            for(Long specValueId : shopProductSaveDTO.getSpecValueIds()){
                ShopProductSpec shopProductSpec = new ShopProductSpec();
                shopProductSpec.setProductId(shopProduct.getId());
                ShopSpecValue shopSpecValue = shopSpecValueService.getById(specValueId);
                shopProductSpec.setSpecId(shopSpecValue.getSpecId());
                shopProductSpec.setSpecValueId(specValueId);
                shopProductSpec.setHasImg(1);
                if(shopSpecValue.getProductId() == -1){
                    shopSpecValue.setProductId(shopProduct.getId());
                    shopSpecValueService.updateById(shopSpecValue);
                }
                shopProductSpecService.save(shopProductSpec);
            }
        }
        return R.successDef();
    }


    @Override
    public R<ShopProduct> handlerUpdate(ShopProductUpdateDTO model) {
        String abc = "style=\"\"";
        String desc = model.getProductDesc();
        if(desc.indexOf(abc) > 0){
            desc = desc.replaceAll("style=\"\"","style=\"width:100%;\"");
        }else{
            if(desc.indexOf("style") > 0){

            }else{
                desc = desc.replaceAll("img ","img style=\"width:100%;\" ");
            }
        }
        model.setProductDesc(desc);
        return R.successDef();
    }

    @Override
    public R<ShopProduct> handlerAfterUpdate(ShopProductUpdateDTO shopProductUpdateDTO, ShopProduct shopProduct) {
        if(shopProduct.getId() != null){
            List<ShopProductStockUpdateDTO> shopProductStockList  = shopProductUpdateDTO.getShopProductStockList();
            if(shopProductUpdateDTO.getFlushStock()){
                shopProductStockService.remove(Wraps.<ShopProductStock>lbQ().eq(ShopProductStock::getProductId,shopProduct.getId()));
                for(ShopProductStockUpdateDTO shopProductStockUpdateDTO : shopProductStockList){
                    ShopProductStock model = BeanUtil.toBean(shopProductStockUpdateDTO, ShopProductStock.class);
                    model.setProductId(shopProduct.getId());
                    shopProductStockService.save(model);
                }
            }else{
                for(ShopProductStockUpdateDTO shopProductStockUpdateDTO : shopProductStockList){
                    ShopProductStock model = BeanUtil.toBean(shopProductStockUpdateDTO, ShopProductStock.class);
                    shopProductStockService.updateById(model);
                }

            }
            List<ShopProductGalleryUpdateDTO> shopProductGalleryUpdateDTOS = shopProductUpdateDTO.getShopProductGalleryList();
            List<ShopProductGallery> shopProductGalleryList = shopProductGalleryService.list(Wraps.<ShopProductGallery>lbQ().eq(ShopProductGallery::getProductId,shopProduct.getId()));
            for(ShopProductGallery shopProductGallery : shopProductGalleryList){
                boolean exit = false;
                for(ShopProductGalleryUpdateDTO shopProductGalleryUpdateDTO : shopProductGalleryUpdateDTOS){
                    if(shopProductGalleryUpdateDTO.getId() != null && shopProductGalleryUpdateDTO.getId().equals(shopProductGallery.getId())){
                        exit = true;
                        break;
                    }
                }
                if(exit == false){
                    shopProductGalleryService.removeById(shopProductGallery);
                }
            }


            for(ShopProductGalleryUpdateDTO shopProductGalleryUpdateDTO : shopProductGalleryUpdateDTOS){
                if(shopProductGalleryUpdateDTO.getId() == null){
                    ShopProductGallery model = BeanUtil.toBean(shopProductGalleryUpdateDTO, ShopProductGallery.class);
                    model.setProductId(shopProduct.getId());
                    shopProductGalleryService.save(model);
                }
            }
            List<ShopProductSpec> shopProductSpecList = shopProductSpecService.list(Wraps.<ShopProductSpec>lbQ().eq(ShopProductSpec::getProductId,shopProduct.getId()));
            for(ShopProductSpec shopProductSpec : shopProductSpecList){
                boolean exit = false;
                for(Long specValueId : shopProductUpdateDTO.getSpecValueIds()){
                    if(specValueId.equals(shopProductSpec.getSpecValueId())){
                        exit = true;
                    }
                }
                if(!exit){
                    shopProductSpecService.removeById(shopProductSpec);
                }
            }
            for(Long specValueId : shopProductUpdateDTO.getSpecValueIds()){

                ShopSpecValue shopSpecValue = shopSpecValueService.getById(specValueId);
                if(shopSpecValue != null && shopSpecValue.getProductId() != null && shopSpecValue.getProductId() == -1){
                    shopSpecValue.setProductId(shopProduct.getId());
                    shopSpecValueService.updateById(shopSpecValue);
                }
                List<ShopProductSpec> shopProductSpecList1 = shopProductSpecService.list(Wraps.<ShopProductSpec>lbQ().eq(ShopProductSpec::getProductId,shopProduct.getId()).eq(ShopProductSpec::getSpecValueId,specValueId));
                if(shopProductSpecList1.size() == 0){
                    ShopProductSpec shopProductSpec = new ShopProductSpec();
                    shopProductSpec.setProductId(shopProduct.getId());
                    shopProductSpec.setSpecId(shopSpecValue.getSpecId());
                    shopProductSpec.setSpecValueId(specValueId);
                    shopProductSpec.setHasImg(1);
                    shopProductSpecService.save(shopProductSpec);
                }
            }
        }
        return R.successDef();
    }

    @PostMapping(value = "verify")
    public R<Boolean> verify(@RequestBody ShopProductUpdateDTO shopProductUpdateDTO){
        ShopProduct shopProduct = baseService.getById(shopProductUpdateDTO.getId());
        shopProduct.setStatus(shopProductUpdateDTO.getStatus());
        shopProduct.setSpellArea(shopProductUpdateDTO.getSpellArea());
        shopProduct.setPriceId(shopProductUpdateDTO.getPriceId());
        shopProduct.setSpellProduct(shopProductUpdateDTO.getSpellProduct());
        baseService.updateById(shopProduct);
        return R.successDef();
    }
    /**
     * 分页查询
     *
     * @param params
     * @return
     */
    @ApiOperation(value = "分页列表查询商品明细")
    @PostMapping(value = "/shopProductDetailPage")
    //@SysLog(value = "'分页列表查询:第' + #params?.current + '页, 显示' + #params?.size + '行'", response = false)
    //@PreAuth("hasPermit('{}view')")
    public R<IPage<ShopProductDetail>> shopProductDetailPage(@RequestBody @Validated PageParams<ShopProductDetailPageDTO> params) {
        // 处理参数
        String pfx = String.valueOf(redisService.hget(RedisConstant.SYS_CONFIG_1, RedisConstant.WEBSIT_URL));
        IPage<ShopProductDetail> page = params.buildPage();
        //query1(params, page, null);
        /*CurrentUser currentUser = CnswhyUtil.getCurrentUser();
        if(currentUser != null){
            log.info(JSON.toJSONString(currentUser));
            if(currentUser != null && currentUser.getMerchantId() != null){
                params.getModel().setMerchantId(currentUser.getMerchantId());
            }
        }*/
        page = shopProductMapper.getShopProductDetails(page,params.getModel());
        for(ShopProductDetail shopProductDetail : page.getRecords()){
            List<ShopProductGallery> shopProductGalleryList = shopProductGalleryService.list(Wraps.<ShopProductGallery>lbQ().eq(ShopProductGallery::getProductId,shopProductDetail.getId()));
            /*for(ShopProductGallery shopProductGallery : shopProductGalleryList){
                shopProductGallery.setUpdateTime(null);
                shopProductGallery.setCreateTime(null);
            }*/
            shopProductDetail.setShopProductGalleryList(shopProductGalleryList);
            List<ShopProductSpec> shopProductSpecList = shopProductSpecService.list(Wraps.<ShopProductSpec>lbQ().eq(ShopProductSpec::getProductId,shopProductDetail.getId()));
            /*for(ShopProductSpec shopProductSpec : shopProductSpecList){
                shopProductSpec.setUpdateTime(null);
                shopProductSpec.setCreateTime(null);
            }*/
            shopProductDetail.setShopProductSpecList(shopProductSpecList);
            List<ShopProductStock> shopProductStockList =  shopProductStockService.list(Wraps.<ShopProductStock>lbQ().eq(ShopProductStock::getProductId,shopProductDetail.getId()));
           /* for(ShopProductStock shopProductStock : shopProductStockList){
                shopProductStock.setUpdateTime(null);
                shopProductStock.setCreateTime(null);
            }*/
            shopProductDetail.setShopProductStockList(shopProductStockList);
            shopProductDetail.setH5Url(pfx + "/#/pages/productInfo/productInfo?id=" + shopProductDetail.getId());
        }
        return success(page);
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<ShopProduct> shopProducts = list.stream().map((map) -> {
            ShopProduct shopProduct = ShopProduct.builder().build();
            return shopProduct;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(shopProducts));
    }
}
